#  做页面静态化处理 ：提前渲染页面，保存为静态HTML，供用户访问
from collections import OrderedDict
from django.conf import settings
from django.template import loader
import os
import time

from goods.models import GoodsChannel
from .models import ADContentCategory, ADContent


def generate_static_index_html():
    """
    生成静态的主页html文件
    """
    print('%s: generate_static_index_html' % time.ctime())
    # 商品频道及分类菜单
    # 使用有序字典保存类别的顺序
    # categories = {
    #     1: { # 组1
    #         'channels': [{'id':, 'name':, 'url':},{}, {}...],
    #         'sub_cats': [{'id':, 'name':, 'sub_cats':[{},{}]}, {}, {}, ..]
    #     },
    #     2: { # 组2
    #
    #     }
    # }
    categories = OrderedDict()
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    # 手机通讯中的时尚新品
    content_list =[]
    # 手机通讯中的畅享低价
    content_list_fl = []
    #  手机配件 数据
    content_list_pj = []
    # 2楼加价换购  16
    content_list_hg = []
    # 2楼畅享低价 18
    content_list_dj = []
    # 3楼生活用品
    content_list_sh = []
    # 3楼厨房用品
    content_list_cf = []
    for channel in channels:
        group_id = channel.group_id  # 当前组

        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        cat1 = channel.category  # 当前频道的类别

        # 追加当前频道
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })
        # 构建当前类别的子类别
        for cat2 in cat1.goodscategory_set.all():
            cat2.sub_cats = []
            for cat3 in cat2.goodscategory_set.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)

    # from contents.crons import generate_static_index_html
    category1 = [8, 10, 11,16,18,24,25]
    for i in category1:
        content = ADContent.objects.filter(category_id=i)
        # print(content)
        for j in content:
            print(j)
            print(type(j))

            title = j.title
            image = j.image
            category = j.category_id
            # print(title)
            # print(category)
            text = j.text

            content_data = {
                    'title':title,
                    'image':image,
                    'category':category,
                    'text':text
            }
            if category == 8:
                content_list.append(content_data)
            # content_list_fl
            elif category ==10:
                content_list_fl.append(content_data)
            # content_list_pj
            elif category == 11:
                content_list_pj.append(content_data)
            # content_list_hg
            elif category == 16:
                content_list_hg.append(content_data)
            # content_list_dj
            elif category == 18:
                content_list_dj.append(content_data)
            # content_list_sh
            elif category == 24:
                content_list_sh.append(content_data)
            # content_list_cf
            elif category == 25:
                content_list_cf.append(content_data)
    print(content_list)
    print(content_list_fl)
    # 广告内容
    contents = {}
    content_categories = ADContentCategory.objects.all()
    for cat in content_categories: # cat 是 ADContentCategory的实例
        # 通过一那方的实例.多的那方全小写类名_set来反向查询一 下面 多 那方的所有详情：查询cat广告分类实例下排序后展示ADContent广告内容信息
        contents[cat.key] = cat.adcontent_set.filter(status=True).order_by('sequence')
    # 广告图片查询
    contents_url = []

    content = ADContent.objects.filter(category_id=1)
        # print(content)
    for j in content:
        title = j.title
        image = j.image
        category = j.category_id
            # print(title)
            # print(category)
        content_data = {
                'title':title,
                'image':image,
                'category':category
        }
        contents_url.append(content_data)
    # print(contents_url)
    # 渲染模板
    context = {
        'categories': categories,
        'contents': contents,
        'content_data':content_list,
        'contents_url':contents_url,
        'content_list_fl':content_list_fl,
        'content_list_pj':content_list_pj,
        'content_list_hg':content_list_hg,
        'content_list_dj':content_list_dj,
        'content_list_cf':content_list_cf,
        'content_list_sh':content_list_sh,
    }
    # 在配置文件Templates中找DIRS的配置模板的路径来渲染内容
    template = loader.get_template('index.html')  # 这个用来渲染数据的文件
    html_text = template.render(context)
    # 通过配置文件GENERATED_STATIC_HTML_FILES_DIR配置前端路径--指定前端的index.html
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)